"""部署时执行备份操作"""
import os
from src.core import log
from sqlalchemy import and_
from src.db import dbm, dbs
from src.mod import safe_remove
from src.core.variables.status import *
from src.core.variables.constant import *
from src.core.variables.function import CREATE_ID
from src.core.variables.exception import MAIN_EXCEPTION


class Java:
    def __init__(self, app_id) -> None:
        self._app_id = app_id

    def current_data(self):
        """备份当前信息到app_backup库"""
        with dbm.get("hosting_Java") as db_session:
            from sqlalchemy.orm import scoped_session
            db_session: scoped_session
            old_app = (
                db_session.query(dbs.hosting_Java.App)
                .filter(dbs.hosting_Java.App.app_id == self._app_id)
                .first()
            )
            if not old_app:
                raise ValueError(f"应用 {self._app_id} 不存在，无法备份。")
            old_app_dict = old_app.__dict__
            old_app_dict.pop("_sa_instance_state", None)
            backup_app = dbs.hosting_Java.App_backup(**old_app_dict)
            backup_app.back_id = CREATE_ID()
            self.back_id = backup_app.back_id
            db_session.add(backup_app)
            if dbm.commit(db_session):
                log.INFO(f"应用 {self._app_id} 配置备份完成！")
            else:
                raise MAIN_EXCEPTION(f"提交数据库更改失败！")
            return self

    def databases(self):
        """备份app运行所用的数据库的指定库和表"""
        ...
        return self

    # 其他备份操作...


def java_remove(schema):
    """删除java指定back_id的备份"""
    with dbm.get("hosting_Java") as db_session:
        from sqlalchemy.orm import scoped_session
        db_session: scoped_session
        db_result = (
            db_session.query(dbs.hosting_Java.App_backup)
            .filter(
                and_(
                    dbs.hosting_Java.App_backup.back_id == schema.back_id,
                )
            )
            .first()
        )
        if not db_result:
            return ERROR_CODE_CUSTOMIZE("指定的备份记录不存在", 404)
        remove_dict = {
            "log_path": db_result.log_path,
            "repo_path": f"{CONF.PATH.REPO}{db_result.alias}/{db_result.time_dir}"
        }
        for index, value in remove_dict.items():
            if value and os.path.exists(value):
                remove_result, remove_message = safe_remove(value, is_dir=True)
                if not remove_result:
                    log.WARNING(f"删除{index} 文件 {value} 失败，{remove_message}")
            elif value:
                log.WARNING(f"删除{index} 文件 {value} 失败，文件不存在。")
        successor = db_session.query(dbs.hosting_Java.App_backup).filter(
            dbs.hosting_Java.App_backup.before_id == db_result.back_id
        ).first()
        if successor:
            successor.before_id = db_result.before_id
        db_session.delete(db_result)
        if dbm.commit(db_session):
            return SUCCESS_CODE_CUSTOMIZE("删除成功", 200)
        else:
            raise MAIN_EXCEPTION(f"提交数据库更改失败！")


class Static:
    def __init__(self, app_id) -> None:
        self._app_id = app_id

    def current_data(self):
        """备份当前信息到app_backup库"""
        with dbm.get("hosting_Static") as db_session:
            old_app = (
                db_session.query(dbs.hosting_Static.App)
                .filter(dbs.hosting_Static.App.app_id == self._app_id)
                .first()
            )
            if not old_app:
                raise ValueError(f"应用 {self._app_id} 不存在，无法备份。")
            old_app_dict = old_app.__dict__
            old_app_dict.pop("_sa_instance_state", None)
            backup_app = dbs.hosting_Static.App_backup(**old_app_dict)
            backup_app.back_id = CREATE_ID()
            self.back_id = backup_app.back_id
            db_session.add(backup_app)
            if dbm.commit(db_session):
                log.INFO(f"应用 {self._app_id} 配置备份完成！")
            else:
                raise MAIN_EXCEPTION(f"提交数据库更改失败！")
            return self
        

def static_remove(schema):
    """删除static指定back_id的备份"""
    with dbm.get("hosting_Static") as db_session:
        from sqlalchemy.orm import scoped_session
        db_session: scoped_session
        db_result = (
            db_session.query(dbs.hosting_Static.App_backup)
            .filter(
                and_(
                    dbs.hosting_Static.App_backup.back_id == schema.back_id,
                )
            )
            .first()
        )
        if not db_result:
            return ERROR_CODE_CUSTOMIZE("指定的备份记录不存在", 404)
        from src.core.variables.constant import CONF
        remove_dict = {
            "repo_path": f"{CONF.PATH.REPO}{db_result.alias}/{db_result.time_dir}",
        }
        for index, value in remove_dict.items():
            if value and os.path.exists(value):
                remove_result, remove_message = safe_remove(value, is_dir=True)
                if not remove_result:
                    log.WARNING(f"删除{index} 文件 {value} 失败，{remove_message}")
            elif value:
                log.WARNING(f"删除{index} 文件 {value} 失败，文件不存在。")
        # 修复删除逻辑：正确维护链式关系
        # 查找直接后继版本（指向当前要删除版本的版本）
        successor = db_session.query(dbs.hosting_Static.App_backup).filter(
            dbs.hosting_Static.App_backup.before_id == db_result.back_id
        ).first()
        
        # 如果存在直接后继版本，则将其before_id更新为当前版本的before_id
        if successor:
            successor.before_id = db_result.before_id
            
        # 删除当前版本记录
        db_session.delete(db_result)
        if dbm.commit(db_session):
            return SUCCESS_CODE_CUSTOMIZE("删除成功", 200)
        else:
            raise MAIN_EXCEPTION(f"提交数据库更改失败！")
